package test.testList;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class FileContent {
//    public static void main(String[] args) {
//        try {
//            Map<String,String> replaceMap = new HashMap<>();
//            replaceMap.put("busin_pty","bpty");
//            replaceMap.put("BUSIN_PTY","BPTY");
//            replaceMap.put("BusinPty","Bpty");
//            replaceMap.put("businPty","bpty");
//            replaceText("D:\\TDA5.0\\tda-new\\trust-tda-biz-server\\schema\\deploy\\5.0.0\\oracle\\2.3tda-dgmm\\1.2CommonScript\\08.存储过程和包\\p_dgmm_busin_pty_map_prtc.pck",
//                replaceMap,
//                "gbk");
//        }
//        catch (Exception e){
//            e.printStackTrace();
//        }
//    }

    public static void replaceText(String filePath,Map<String,String> replaceMap,String charsetName) throws Exception{
        try {
            //File fromFile = new File("D:\\TDA5.0\\tda-new\\trust-tda-biz-server\\schema\\deploy\\5.0.0\\oracle\\2.3tda-dgmm\\1.2CommonScript\\08.存储过程和包\\p_dgmm_busin_pty.pck");
            //File toFile = new File("D:\\TDA5.0\\tda-new\\trust-tda-biz-server\\schema\\deploy\\5.0.0\\oracle\\2.3tda-dgmm\\1.2CommonScript\\08.存储过程和包\\p_dgmm_busin_pty2.pck");
            File fromFile = new File(filePath);
            File toFile = new File(fromFile.getParent() + File.separator + UUID.randomUUID().toString().replace("-",""));
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fromFile),charsetName));
            BufferedWriter bufferedWriter = new BufferedWriter((new OutputStreamWriter(new FileOutputStream(toFile), charsetName)));
            String str = null;
            int index =0;
            while((str = bufferedReader.readLine()) != null) {
                index ++;
                //这是读取的内容
                //System.out.println("---------------------------------------------------");
                //System.out.println(str);
                for (String key:replaceMap.keySet()) {
                    str = str.replace(key,replaceMap.get(key));
                }
                //System.out.println(str);
                if (index>1){
                    bufferedWriter.newLine();
                }
                bufferedWriter.write(str);
            }
            bufferedReader.close();
            bufferedWriter.close();
            String toFilePath = toFile.getAbsolutePath();
            fromFile.delete();
            //fromFile.createNewFile();
            toFile.renameTo(fromFile);
            new File(toFilePath).delete();
        }
        catch (Exception e){
            throw e;
        }
    }
}
